import type { DeckDetail } from '/@/api/currentDeck/model/deckModel';
import ClipboardJS from 'clipboard';
import { useUserStore } from '/@/store/modules/user';
import { useGlobSetting } from '/@/hooks/setting';
import { defineComponent, reactive, ref, onMounted, computed } from 'vue';
import { useCurrentDeckStore } from '/@/store/modules/currentDeck';
import { useDeckSetStore } from '/@/store/modules/deckSet';
import { useRouter } from 'vue-router';
import { useCurrentDeckConfigHooks } from '/@/views/currentDeck/hooks/useConfigs';
import { appShareParamsEncrypt, appShareUsing } from '/@/utils/appInteractive';
import { useMessage } from '/@/hooks/web/useMessage';
import { useExportHooks } from '/@/views/deskSet/hooks/useExport';
import { aTabClick, awaitWrap, textExtractUrl } from '/@/utils';
import { DeckDetailApi } from '/@/api/currentDeck/deck';
import { SetDeckLikeApi, SetDeckCopyApi } from '/@/api/deckSet/setDeck';
import { isArray } from '/@/utils/is';
import { formatToDateTime } from '/@/utils/dateUtil';
import { Skeleton, Tag } from 'vant';
import { Icon } from '/@/components/Icon';
import Title from '/@/views/general/components/Title';
import DeckSelectedCardList from '/@/views/currentDeck/components/DeckSelectedCardList';

import('./index.less');

export default defineComponent({
  name: 'SetDeckDetailPage',
  props: {
    deckId: {
      type: String as PropType<string>,
      required: true,
    },
    share: {
      type: String as PropType<string>,
      default: () => {
        return '';
      },
    },
    gameId: {
      type: String as PropType<string>,
      default: () => {
        return '';
      },
    },
  },
  setup(props) {
    onMounted(() => {
      document.querySelector('.set-deck-back-top')?.setAttribute('style', 'visibility: hidden');
    });

    const userStore = useUserStore();

    const router = useRouter();
    const { createInfoToast, createSuccessToast, createFailToast } = useMessage();

    const currentStore = useCurrentDeckStore();
    const setStore = useDeckSetStore();
    currentStore.setGameId(setStore.getGameId || props.gameId);
    setStore.getGameId ? useCurrentDeckConfigHooks({ game_id: setStore.getGameId || props.gameId }) : null;

    // 分享地址
    const shareUrl = `${useGlobSetting().gadgetsUrl}/templatedeck/index.html#/setdeckdetail/${props.deckId}/${
      setStore.getGameId || props.gameId
    }?share=1`;

    const content = {
      title: '旅法师营地套牌',
      content: '我通过旅法师营地跟你分享了套牌，点击查看',
      image: 'https://pic.iyingdi.com/yingdi_mobile/yingdi-logo.png',
      url: shareUrl,
    };

    // 如果是分享页面则重新获取配置
    if (props.share) {
      currentStore.setGameId(props.gameId);
      setStore.setGameId(props.gameId);
      const {} = useCurrentDeckConfigHooks({ game_id: props.gameId });
    }
    // 设置分享参数
    appShareUsing(content);

    // 导出组件
    const { UseExport } = useExportHooks();

    const deckDetailInfo = reactive<DeckDetail>({} as DeckDetail);
    const loadingState = ref(true);
    const getDetail = async () => {
      const [error, data] = await awaitWrap(DeckDetailApi({ deck_id: Number(props.deckId) }));
      if (error) {
        return false;
      }
      const result = data as DeckDetail;
      for (const item in result) {
        deckDetailInfo[item] = result[item];
      }
      deckDetailInfo.tags = isArray(result.tags) ? result.tags : [];
      loadingState.value = false;
    };
    getDetail();

    // 卡牌标题
    const DeckBasicInfoArea = () => {
      return (
        <ul class={'deck-basic-info-area'}>
          <li class={'flex justify-between'}>
            <div class={'flex-1'}>
              <span class={'font-bold'}>套牌名称：</span>
              {deckDetailInfo.deck_name}
            </div>
          </li>
          <li class={'flex justify-between'}>
            <div class={'flex-1'}>
              <span class={'font-bold'}>
                套牌ID<span class={'mx-[14px]'}></span>：
              </span>
              {deckDetailInfo.deck_id}
              <span onClick={copyDeckId}>
                <Icon class={'!text-sm ml-sm text-blue-500 copy-deck-id'} icon={'ic:round-content-copy'} />
              </span>
            </div>
          </li>
          <li class={'flex justify-between'}>
            <div class={'flex-1'}>
              <span class={'font-bold'}>用户昵称：</span>
              {deckDetailInfo.nickname}
            </div>
          </li>
          {deckDetailInfo.price ? (
            <li>
              <span class={'font-bold'}>预估售价：</span>
              {deckDetailInfo.price ? <>{deckDetailInfo.price / 100}元</> : <span>暂无</span>}
            </li>
          ) : null}
          <li>
            <span class={'font-bold'}>发布时间：</span>
            {formatToDateTime(deckDetailInfo.publish_at, 'YYYY-MM-DD')}
          </li>
          {deckDetailInfo.tags.length ? (
            <li>
              <span class={'font-bold'}>
                标 <span class={'mx-lg'}></span> 签：
              </span>
              {deckDetailInfo.tags.map((text) => {
                return (
                  <Tag color={'linear-gradient(142deg, #4396ff 0%, #086acc 100%)'} class='mr-sm'>
                    {text}
                  </Tag>
                );
              })}
            </li>
          ) : null}
        </ul>
      );
    };

    // 复制套牌ID
    const copyDeckId = () => {
      const clipboard = new ClipboardJS('.copy-deck-id', {
        text: function () {
          return String(deckDetailInfo.deck_id);
        },
      });
      clipboard.on('success', function () {
        createSuccessToast({
          message: '套牌ID已复制',
        });
      });
      clipboard.on('error', function () {
        createFailToast({
          message: '复制套牌ID失败',
        });
      });
    };

    // 赞踩逻辑
    const DeckLikeHate = () => {
      const { is_like, likes_number } = deckDetailInfo;
      let activeStyle = '';
      if (is_like === 1) {
        activeStyle = 'like';
      } else if (is_like === 2) {
        activeStyle = 'dislike';
      }
      return (
        <li class={`like-box flex text-white ${activeStyle}`}>
          <div class={'like flex-1 flex items-center justify-center'} onClick={likeClick}>
            <Icon icon={'bx:like'} class={'!text-45px'} />
            {likes_number ? <span class={'text-sm ml-sm'}>{likes_number}</span> : null}
          </div>
          <div class={'dislike flex-1 flex items-center justify-center'} onClick={disLikeClick}>
            <Icon icon={'bx:dislike'} class={'!text-45px'} />
          </div>
        </li>
      );
    };

    // 分享事件
    const shareClick = () => {
      content.title = deckDetailInfo.deck_name;
      content.url = shareUrl;
      const base64str = appShareParamsEncrypt(JSON.stringify(content));
      aTabClick(`wanxiu://innerlink?type=webshareurl&parameters=${base64str}`);
    };
    // 复制套牌
    const copyDeck = async () => {
      if (!userStore.getToken) {
        aTabClick('wanxiu://innerlink?type=weblogin');
        return false;
      }
      const [error] = await awaitWrap(SetDeckCopyApi({ deck_id: deckDetailInfo.deck_id }));
      if (error) {
        return;
      }
      createInfoToast({
        overlay: true,
        message: '复制成功, 请到我的套牌查看',
      });
    };

    // 点赞点踩
    const likeClick = () => {
      if (!userStore.getToken) {
        aTabClick('wanxiu://innerlink?type=weblogin');
        return false;
      }
      const { is_like, deck_id } = deckDetailInfo;
      let val = 0;
      if (is_like === 1) {
        val = 0;
        deckDetailInfo.likes_number -= 1;
      } else {
        val = 1;
        deckDetailInfo.likes_number += 1;
      }
      deckDetailInfo.is_like = val as any;
      SetDeckLikeApi({ deck_id: deck_id, is_like: 1 });
    };
    const disLikeClick = () => {
      if (!userStore.getToken) {
        aTabClick('wanxiu://innerlink?type=weblogin');
        return false;
      }
      const { is_like, deck_id } = deckDetailInfo;
      let val = 0;
      if (is_like === 1) {
        val = 2;
        deckDetailInfo.likes_number -= 1;
      } else if (is_like === 2) {
        val = 0;
      } else if (!is_like) {
        val = 2;
      }
      deckDetailInfo.is_like = val as any;
      SetDeckLikeApi({ deck_id: deck_id, is_like: 2 });
    };

    // 是否有返回按钮
    const isLeftArrow = computed(() => {
      const { gameId, share } = props;
      return !(gameId || share);
    });

    return () => (
      <div class={'set-deck-detail-page'}>
        <Title
          title={deckDetailInfo.deck_name}
          leftArrow={isLeftArrow.value}
          onLeftClick={() => {
            router.go(-1);
          }}
        />
        <Skeleton title row={5} avatar loading={loadingState.value}>
          <div class={'detail-container'}>
            <DeckBasicInfoArea />
            {deckDetailInfo.deck_desc ? (
              <div
                class='deck-basic-info-area whitespace-pre-line break-all'
                v-html={textExtractUrl(deckDetailInfo.deck_desc)}
              ></div>
            ) : null}
            <DeckSelectedCardList deckCardList={deckDetailInfo.deck_info} />
          </div>
        </Skeleton>
        {!props.share ? (
          <ul class={'action-area  flex items-center justify-between'}>
            <li class={'exprot'}>
              <UseExport gameId={setStore.getGameId || props.gameId} deckId={props.deckId} />
            </li>
            <li class={'share flex flex-col items-center'} onClick={copyDeck}>
              <Icon class={'!text-xl mb-sm'} icon={'ic:round-content-copy'} />
              <span>复制</span>
            </li>
            <li class={'share flex flex-col items-center'} onClick={shareClick}>
              <Icon class={'!text-xl mb-sm'} icon={'ri:share-circle-line'} />
              <span>分享</span>
            </li>
            <DeckLikeHate />
          </ul>
        ) : null}
      </div>
    );
  },
});
